import threading
import time
import sys

# 计数器，用于记录创建的线程数量
thread_count = 0

def worker():
    global thread_count
    thread_id = threading.get_ident()
    print(f"线程 {thread_id} 启动")
    try:
        while True:
            time.sleep(1)  # 保持线程活跃
    except KeyboardInterrupt:
        print(f"线程 {thread_id} 退出")

try:
    while True:
        try:
            # 创建并启动一个新线程
            t = threading.Thread(target=worker)
            t.daemon = True  # 设置为守护线程，主线程退出时自动结束
            t.start()
            thread_count += 1
            print(f"已创建 {thread_count} 个线程")
        except Exception as e:
            print(f"无法创建更多线程: {e}")
            break
except KeyboardInterrupt:
    print("测试中断")

print(f"最多可以创建 {thread_count} 个线程")